using System;
using App.Modelo.Interfaces;
using NHibernate.Event;
using NHibernate.Event.Default;

namespace App.Persistencia
{
    public class CustomDeleteEventListener : DefaultDeleteEventListener
    {
        protected override void DeleteEntity(IEventSource session, object entity,
                                             NHibernate.Engine.EntityEntry entityEntry,
                                             bool isCascadeDeleteEnabled,
                                             NHibernate.Persister.Entity.IEntityPersister persister,
                                             Iesi.Collections.ISet transientEntities)
        {
            var auditableEntity = entity as IBorradoLogico;

            if (auditableEntity != null)
            {
                ProcessEntityForLogicalDelete(auditableEntity);
                
                this.CascadeBeforeDelete(session, persister, entity,
                                         entityEntry, transientEntities);
                this.CascadeAfterDelete(session, persister, entity,
                                        transientEntities);
            }
            else
            {
                //normal delete
                base.DeleteEntity(session, entity, entityEntry,
                                  isCascadeDeleteEnabled, persister, transientEntities);
            }
        }

        private void ProcessEntityForLogicalDelete(IBorradoLogico entity)
        {
            entity.FechaBaja = DateTime.Now;
        }
    }
    /*
    public class CustomSaveUpdateEventListener : DefaultSaveOrUpdateEventListener
    {
        protected override object PerformSaveOrUpdate(SaveOrUpdateEvent evt)
        {
            var entity = evt.Entity as AuditableEntity;

            if (entity != null)
            {
                if (entity.Id == 0)
                    ProcessEntityForInserting(entity);
                else
                    ProcessEntityForUpdating(entity);
            }

            return base.PerformSaveOrUpdate(evt);
        }

        internal virtual void ProcessEntityForInserting(AuditableEntity entity)
        {
            entity.AddedDate = DateTime.Now;
            entity.AddedBy = SecurityContext.LoggedUser ?? null;
            entity.AddedFromIP = SecurityContext.GetHostIP();
            entity.AddedFromHostName = SecurityContext.GetHostName();
        }

        internal virtual void ProcessEntityForUpdating(AuditableEntity entity)
        {
            entity.ModifiedDate = DateTime.Now;
            entity.ModifiedBy = SecurityContext.LoggedUser ?? null;
            entity.ModifiedFromIP = SecurityContext.GetHostIP();
            entity.ModifiedFromHostName = SecurityContext.GetHostName();
        }
    }
     * */
}